#include "Segment2.h"

namespace PocketSurvival
{
    float Segment2::Distance(const Segment2 &s, const Vector2 &p)
    {
        Vector2 v = s.end - s.start;
        Vector2 v2 = s.start - p;
        Vector2 v3 = s.end - p;
        float num = Vector2::Dot(v2, v);
        if (num * Vector2::Dot(v3, v) <= 0.0f)
        {
            float num2 = v.lengthSquared();
            if (num2 == 0.0f)
            {
                return Vector2::Distance(p, s.start);
            }
            return MathUtils::Abs<float>(Vector2::Cross(p - s.start, v)) / MathUtils::Sqrt(num2);
        }
        if (!(num > 0.0f))
        {
            return v3.length();
        }
        return v2.length();
    }

    Vector2 Segment2::NearestPoint(const Segment2 &s, const Vector2 &p)
    {
        Vector2 v = s.end - s.start;
        Vector2 v2 = s.start - p;
        Vector2 v3 = s.end - p;
        float num = Vector2::Dot(v2, v);
        if (num * Vector2::Dot(v3, v) <= 0.0f)
        {
            float num2 = v.length();
            if (num2 == 0.0f)
            {
                return s.start;
            }
            float num3 = MathUtils::Sqrt(v2.lengthSquared() - MathUtils::Sqr(MathUtils::Abs(Vector2::Cross(p - s.start, v)) / num2));
            return Vector2::Lerp(s.start, s.end, num3 / num2);
        }
        if(!(num > 0.0f))
        {
            return s.end;
        }
        return s.start;
    }
}
